import axios from "axios";

export const axiosResourceIns = axios.create({
  baseURL: import.meta.env.PROD
    ? `${import.meta.env.VITE_SERVER_BUSINESS}/api/v1/business/biz`
    : "/api/v1/business/biz",
});

axiosResourceIns.interceptors.request.use(
  function (config) {
    config.headers.set("token", MyModule.storage.getItem("token", ""));
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

axiosResourceIns.interceptors.response.use(
  (response) => {
    if (response.data?.code === 401 || response.data?.code === 403) {
      MyModule.storage.removeItem("token");
      location.reload();
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const axiosProductIns = axios.create({
  baseURL: import.meta.env.PROD
    ? `${import.meta.env.VITE_SERVER_MODEL}/api/v1/model/biz`
    : "/api/v1/model/biz",
});

axiosProductIns.interceptors.request.use(
  function (config) {
    config.headers.set("token", MyModule.storage.getItem("token", ""));
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

axiosProductIns.interceptors.response.use(
  (response) => {
    if (response.data?.code === 401 || response.data?.code === 403) {
      MyModule.storage.removeItem("token");
      location.reload();
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const axiosAccountIns = axios.create({
  baseURL: import.meta.env.PROD
    ? `${import.meta.env.VITE_SERVER_ACCOUNT}/api/v1/account`
    : "/api/v1/account",
});

axiosAccountIns.interceptors.request.use(
  function (config) {
    config.headers.set("token", MyModule.storage.getItem("token", ""));
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

axiosAccountIns.interceptors.response.use(
  (response) => {
    if (response.data?.code === 401 || response.data?.code === 403) {
      MyModule.storage.removeItem("token");
      location.reload();
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);
